﻿using DotNetty.Transport.Channels;
using InkjetControl.bean;
using InkjetControl.codec;
using InkjetControl.events;
using InkjetControl.NLog;
using Newtonsoft.Json;

namespace InkjetControl.services.resolvers
{
    public class ResponseMessageResolver : IResolver
    {
        public Message Resolve(Message message)
        {
            Log.Logger.Debug("Srv resolve: [ sessionID:{0}], mc:{1}, ml:{2}, recv body:{3}", message.SessionId, message.MachineCode, message.MachineLabel, message.Body);

            ProcessMessage(message);

            return new Message() { MessageType = MessageType.EMPTY };
        }

        public bool Support(Message message)
        {
            return MessageType.RESPONSE == message.MessageType;
        }

        private IBody ProcessMessage(Message msg)
        {
            Body<object> msgBody = (Body<object>)msg.Body;
            if (msg.Body == null)
            {
                string info = "Error: unknown command";
                return Message.GenerateMsgBody(NetCmd.UNKNOWN_CMD, data: ref info);
            }

            switch (msgBody.Cmd)
            {
                case NetCmd.START_SUPPLY_INK:
                    EventBus.OnStartSupplyInk(msg.MachineCode);
                    break;
                case NetCmd.STOP_SUPPLY_INK:
                    EventBus.OnStopSupplyInk(msg.MachineCode);
                    break;
                case NetCmd.START_PRINT:
                    EventBus.OnStartPrint(msg.MachineCode, msgBody.Data?.ToString());
                    break;
                case NetCmd.STOP_PRINT:
                    EventBus.OnStopPrint(msg.MachineCode);
                    break;
                case NetCmd.REFRESH_STATUS:
                    break;
                case NetCmd.GET_PRINT_PARAMS:
                    PrintParamsBean printParams;
                    printParams = JsonConvert.DeserializeObject<PrintParamsBean>(msgBody.Data?.ToString());
                    EventBus.OnGetPrintParams(msg.MachineCode, printParams);
                    break;
                case NetCmd.SET_PRINT_PARAMS:
                    EventBus.OnSetPrintParams(msg.MachineCode);
                    break;
                case NetCmd.GET_SYSTEM_PARAMS:
                    break;
                case NetCmd.SET_SYSTEM_PARAMS:
                    break;
                case NetCmd.CONNECTION:

                    break;
            }

            return null;
        }
    }
}
